<script setup lang="ts">
  import { h, ref, watch } from 'vue'
  import { useSendInviteCodeService } from '../services'
  import { ElDivider, ElMessage, FormInstance } from 'element-plus'
  import { verifyPhone } from '@/utils/validate'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
  }>()

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 使用服务
  const { loading, send } = useSendInviteCodeService()

  // 手机号列表
  const phones = ref<Array<string>>([''])

  // 弹窗显示状态
  const visible = ref(false)

  // 关闭事件
  const onClose = () => {
    visible.value = false
    phones.value.forEach((item, index) => {
      phones.value[index] = ''
    })
    emits('update:modelValue', visible.value)
  }

  // 添加手机号事件
  const formRef = ref<FormInstance | null>(null)
  const addPhone = async () => {
    if (formRef.value) {
      phones.value.push('')
    }
  }

  // 移除手机号事件
  const handleRemovePhone = (index: number) => {
    phones.value.splice(index, 1)
  }

  // 发送事件
  const onSend = async () => {
    if (formRef.value) {
      await formRef.value.validate(async (valid) => {
        if (valid) {
          const res = await send(phones.value)
          onClose()
          ElMessage({
            type: res.code === 20000 ? 'success' : 'error',
            message: res.message,
            duration: 5000,
            showClose: true,
            plain: true,
          })
        }
      })
    }
  }

  const phoneValidator = (index: number, callback) => {
    if (!phones.value[index]) {
      callback(new Error('请输入手机号码'))
      return false
    }
    if (!verifyPhone(phones.value[index])) {
      callback(new Error('手机号码格式不正确'))
      return false
    }
    callback()
  }

  watch(props, (value) => {
    visible.value = value.modelValue
  })
</script>

<template>
  <div>
    <h-dialog v-model="visible" title="发送短信" :loading="loading" @close="onClose">
      <el-form
        ref="formRef"
        :model="phones"
        class="modal_form_content send_sms_form"
        inline-message
        label-position="top"
      >
        <!-- 移除prop属性时，会导致表单直接校验成功，不管数据有没有 -->
        <el-form-item
          v-for="(item, index) in phones"
          :key="index"
          :label="`手机号码${index + 1}`"
          :prop="`phones[${index}]`"
          :rules="[
            {
              validator: (rule: any, value: any, callback: any) => phoneValidator(index, callback),
              trigger: ['change', 'blur'],
            },
          ]"
        >
          <div class="form_item_content">
            <el-input
              v-model.trim="phones[index]"
              :maxlength="11"
              placeholder="请输入手机号码"
              @input="phones[index] = phones[index].replace(/[^0-9]/g, '')"
            />
            <div class="operate">
              <el-space :size="0" :spacer="spacer">
                <h-link v-if="phones.length > 1" type="error" @click="handleRemovePhone(index)"
                  >删除</h-link
                >
                <h-link v-if="index === 0" @click="addPhone">添加</h-link>
              </el-space>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton is-modal type="primary" @click="onSend">发送</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </h-dialog>
  </div>
</template>

<style scoped lang="scss">
  .add_phone_container {
    display: flex;
    gap: 5px;
    align-items: center;

    .title {
      font-size: 15px;
    }
  }

  .send_sms_form {
    max-height: 470px;
    overflow: auto;

    :deep(.el-form-item) {
      .el-form-item__content {
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        .form_item_content {
          display: flex;
          width: 100%;
          column-gap: 5px;

          .el-input {
            width: 435px;

            .el-input__wrapper {
              .el-input__inner {
                height: 26px;
                line-height: 26px;
              }
            }
          }

          .operate {
            height: 28px;
            line-height: 28px;
          }
        }
      }
    }
  }
</style>
